package com.xl.processor;

import com.xl.utils.BaseClassScanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;

import java.util.Map;

public class MyComponentBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        //通过扫描工具扫描指定包及其子包下的所有类，收集使用带有@MyComponent注解的类
        Map<String,Class> myComponentAnnotationMap =  BaseClassScanUtils.scanMyComponentAnnotation("com.xl.beans");
        //遍历收集到的类，将带有@MyComponent注解的类注册到Spring容器中
        myComponentAnnotationMap.forEach((k,v)->{
            //将带有@MyComponent注解的类注册到Spring容器中
            //创建BeanDefinition对象
            BeanDefinition beanDefinition = new RootBeanDefinition();
            beanDefinition.setBeanClassName(v.getName());
            beanDefinitionRegistry.registerBeanDefinition(k,beanDefinition);
        });
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

    }
}
